#include "net_server.h"

// TODO: SDLNet_TCP_Close(csd);
// SDLNet_TCP_Close(sd);

Netserver::Netserver(unsigned int port)
{
	// Resolving the host using NULL make network interface to listen
	m_handle.open(0,port);
// 	cerr << ip << endl;
}

boost::shared_ptr<nClient> Netserver::getNewConnections( unsigned int connecttime )
{
	boost::shared_ptr<BeTcpSocket> clientSocket( m_handle.accept());
// 	cerr << "checking new connections" << endl;
	boost::shared_ptr<nClient> n(new nClient(connecttime) );
	if ( clientSocket )
	{
		/* Now we can communicate with the client using csd socket
		* sd will remain opened waiting other connections */

		/* Get the remote address */
		const IPaddress  *remoteIP = clientSocket->getIpAddress();
		if (remoteIP)
		{
			/* Print the address, converting in the host format */
			printf("Host connected: %x %d\n", SDLNet_Read32(&remoteIP->host), SDLNet_Read16(&remoteIP->port));
			n->clientsocket = clientSocket;
			return n;
		}
		else
			fprintf(stderr, "SDLNet_TCP_GetPeerAddress: %s\n", SDLNet_GetError());
	}
	return boost::shared_ptr<nClient>();
}

void Netserver::checkIncomingMessages( boost::shared_ptr<nClient> n, std::vector<std::string>* messages )
{
// 	pthread_mutex_lock( &n->socket_mutex );
	if ( !n->toclose )
	{
			if( n->clientsocket->isReady() )
			{ 
				memset(buffer, 0, sizeof buffer);
				if ( n->clientsocket->recieve( buffer, sizeof buffer) < 1 )
				{
					fprintf(stderr, "SDLNet_TCP_Recv: %s\n", SDLNet_GetError());
					n->toclose =  true;
					n->clientsocket->close();
// 					exit(EXIT_FAILURE);
				}
				else
					messages->push_back(std::string(buffer));
			}
	}	
}

void Netserver::sendMessage( boost::shared_ptr<nClient> n, std::string& msg )
{
// 	msg.append("|");
// 	cerr << "\nSENDING : '" << msg << "' to " << n  << endl;

// 	pthread_mutex_lock( &n->socket_mutex );
	if ( !n->toclose )
	{
		if (n->clientsocket->send((void *)msg.c_str(), msg.size()) < msg.size())
		{
			fprintf(stderr, "SDLNet_TCP_Send: %s\n", SDLNet_GetError());
			n->toclose =  true;
			n->clientsocket->close();

	// 		exit(EXIT_FAILURE);
		}
	}
// 	pthread_mutex_unlock( &n->socket_mutex );
}
